﻿using Alipay.AopSdk.Core;
using Alipay.AopSdk.Core.Domain;
using Alipay.AopSdk.Core.Request;
using Alipay沙箱支付.Web;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using System;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using VoL.Domain.Dtos.PatientReCord;
using VoL.Domain.IServices;
using VOL.Core.Configuration;
using VOL.Core.Utilities;

namespace VOL.WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PatientController : ControllerBase
    {
        private readonly IPayInfoService _payInfoService;
        private readonly IPayItemService _payItemService;
        private readonly ILogger<PatientController> _logger;

        public PatientController(IPayInfoService payInfoService,IPayItemService payItemService,ILogger<PatientController> logger)
        {
            _payInfoService = payInfoService;
            _payItemService = payItemService;
            this._logger = logger;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="partientCode"></param>
        /// <returns></returns>
        [HttpGet]
        public Task<WebResponseContent> GetPayInfo(string partientCode)
        {
            return _payInfoService.GetPayInfo(partientCode);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public Task<WebResponseContent> GetPayItem(int id)
        {
            return _payItemService.GetPayItem(id);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public Task<WebResponseContent> FindPayInfo(int id)
        {
            return _payInfoService.FindPayInfo(id);
        }



        /// <summary>   
        /// 支付宝支付
        /// </summary>
        /// <param name="tradeNo">商户订单号</param>
        /// <param name="subject">订单名称</param>
        /// <param name="totaAamount">付款金额</param>
        /// <param name="body">商品描述</param>
        /// <returns></returns>
        [HttpPost("AlipaySubmit")]
        public IActionResult AlipaySubmit([FromBody] AlipayDto dto)
        {
            _logger.LogInformation($"进入支付方法！");

            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            model.Body = dto.Body.Trim();
            model.Subject = dto.Subject.Trim();
            model.TotalAmount = dto.TotalAmount.Trim();
            model.OutTradeNo = dto.TradeNo.Trim();
            model.ProductCode = "FAST_INSTANT_TRADE_PAY";

            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

            // 修改回调地址配置
            var tmpUrl = Request.Scheme + "://" + Request.Host;

            var returnUrl = "http://localhost:9990/#/PayInfo?id=" + dto.PatientCode;
            // 异步通知地址 - 调用后端接口
            var notifyUrl = tmpUrl + "/api/PayconfigController/NotifyUrl";

            request.SetReturnUrl(returnUrl);
            request.SetNotifyUrl(notifyUrl);
            request.SetBizModel(model);

            try
            {
                _logger.LogInformation($"开始跳转到支付页面！");
                DefaultAopClient client = new DefaultAopClient(AlipayConfig.GatewayUrl, AlipayConfig.AppId, AlipayConfig.PrivateKey, "json", "2.0", AlipayConfig.SignType, AlipayConfig.AlipayPublicKey, AlipayConfig.CharSet, false);

                var response = client.PageExecute(request, null, "post");
                _logger.LogInformation($"组装的支付Form数据：{response.Body}");
                return Ok(new { success = true, formHtml = response.Body });
            }
            catch (Exception ex)
            {
                _logger.LogError($"支付报错：{ex.Message}");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        ///// <summary>
        ///// 同步回调函数,由支付宝客户端立即重定向用户浏览器实现 
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost("ReturnUrl")]
        //public ActionResult ReturnUrl()
        //{


        //    //获取订单号，根据订单号查询订单状态，并更新订单状态
        //    StringValues outTradeNo = "";
        //    Request.Query.TryGetValue("out_trade_no", out outTradeNo);
        //    _payConfirmService.UpdatePaymentStatus(outTradeNo);
        //    ViewBag.PayFlag = 1;
        //    ViewBag.PayStatus = "支付完成-寻龙分金看缠山";
        //    return View();
        //}

        ///// <summary>
        ///// 异步：通信异常或中断时回调函数,支付宝后台调用
        ///// 支付宝的8次异步通知，每个异步通知调用频率:15s 3m 10m 30m 1h 2h 6h 15h
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost("NotifyUrl")]
        //public ActionResult NotifyUrl()
        //{
        //    //应该增加一个判断，判断订单状态是否已经修改为 已支付，如果修改为已支付，那么就不要再去修改订单状态了。
        //    ViewBag.PayFlag = 1;
        //    ViewBag.PayStatus = "支付完成";

        //    return View();
        //}











    }
}
